import store from "@/store";

export const pageListSize = 200;
export let pageConfig = {}; // 节点对应的页码
export let nodeToPage = {};

export default function setPageConfig(nodes) {
  let currentListSize = 0;
  let currentPageNumber = 0;
  let total = 0;
  // 页数对应的json文件
  let currentPageConfig = {};
  // 节点对应的页数
  let currentNodeToPage = {};

  function setPageJsonConfig(node, currentPageNumber, i) {
    const deepCloneNode = JSON.parse(JSON.stringify(node));
    const config = Object.assign(deepCloneNode.dataConfig, {
      total: deepCloneNode.total,
      del: deepCloneNode.del,
      // 这里处理给到页面使用
      title: deepCloneNode.name + (deepCloneNode.userCode ? `[${deepCloneNode.userCode}]` :''),
    });
    if (!currentPageConfig[currentPageNumber]) {
      currentPageConfig[currentPageNumber] = [];
    }
    if (!currentNodeToPage[deepCloneNode.dataConfig.jsonName]) {
      currentNodeToPage[deepCloneNode.dataConfig.jsonName] = currentPageNumber;
    }
    if (i) {
      const jsonNamePrefix = config.jsonName.split("_").slice(0, 3);
      jsonNamePrefix.push(i);
      config.jsonName = jsonNamePrefix.join("_");
      currentPageConfig[currentPageNumber].push(config);
    } else {
      currentPageConfig[currentPageNumber].push(deepCloneNode.dataConfig);
    }
  }

  nodes.forEach((node) => {
    // 如果节点有jsonName 或者是第一个节点
    if (node.dataConfig.jsonName) {
      total = total + node.total;
      const pageNum = node.dataConfig.pageNum;

      // 如果只有一页
      if (pageNum === 1) {
        // 累加当前条目数
        currentListSize = currentListSize + node.total;
        // 如果当前超过了 重置 页数加一
        if (currentListSize > pageListSize) {
          currentPageNumber++;
          currentListSize = 0;
        }
        if(node.id === "0" && currentPageNumber < 1)
        {
          currentPageNumber++;
        }
        setPageJsonConfig(node, currentPageNumber);
      } else {
        currentListSize = 0;
        for (let i = 0; i < pageNum; i++) {
          const a = i;
          currentPageNumber = currentPageNumber + 1;
          setPageJsonConfig(node, currentPageNumber, a + 1);
        }
      }
    }
  });
  pageConfig = JSON.parse(JSON.stringify(currentPageConfig));
  nodeToPage = JSON.parse(JSON.stringify(currentNodeToPage));
  currentNodeToPage = null;
  currentPageConfig = null;
  store.dispatch("page/setTotalSize", Object.keys(pageConfig).length * pageListSize);
};
